import { reqCartList, reqDeleteCartById, reqUpdateCheckedById } from '@/api/index.js'

const state = {
    cartList: []
}
const mutations = {
    GETCARTLIST(state, val) {
        state.cartList = val
    }
}
const actions = {
    async getCartList(context) {
        const res = await reqCartList()
        context.commit('GETCARTLIST', res.data)
    },
    async deleteCartBySkuId(context, skuId) {
        const res = await reqDeleteCartById(skuId)
        if (res.code === 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    async getUpdateChecked(context, { skuId, isChecked }) {
        const res = await reqUpdateCheckedById(skuId, isChecked)
        if (res.code === 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    deleteCartThatAreChecked(context) {
        // context不仅能调用Mutation里的，还能调用actions里的，你可以console.log(context)
        // 从某种程度上来说，context也是个仓库
        let promiseAll = []
        context.getters.cartInfoList.forEach((item) => {
                let promise = item.isChecked == 1 ? context.dispatch('deleteCartBySkuId', item.skuId) : '';
                promiseAll.push(promise)
            })
            // 只要p1，p2，p3...都成功，返回结果也是成功；如果有一个失败，就会返回失败结果
        return Promise.all(promiseAll)
    },
    updateAllCartChecked(context, checked) {
        let promiseAll = []
        context.getters.cartInfoList.forEach((item) => {
            let promise = context.dispatch('getUpdateChecked', { skuId: item.skuId, isChecked: checked })
            promiseAll.push(promise)
        })
        return Promise.all(promiseAll)
    }
}
const getters = {
    cartInfoList(state) {
        return state.cartList[0].cartInfoList || {}
    }
}

export default {
    state,
    mutations,
    actions,
    getters
}